/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse;

import java.io.File;
import java.util.*;
import java.sql.*;
import java.util.Properties;

import nfse.*;

/************
 * Searches run from the UI or some API functions use relational database tables
 * to store results. This can fill up local disk over time. This process runs
 * continuously and deletes old tables that have not been accessed recently or
 * marked as permanent.
 * 
 * @author bduphoff
 * 
 */
public class TempDBDelete extends Thread {

	private long lastRun = -1;

	public static void main(String[] args) {
		try {

			NetFSE.configure(args[0]);

			String nodeConfigPath = args[1];
			File config2 = new File(nodeConfigPath);
			if (config2.exists()) {
				NetFSE.processNodeConfigFile(config2);
			} else {
				throw (new Exception(
						"The specified node configuration file does not exist: '"
								+ nodeConfigPath + "'"));
			}

			TempDBDelete del = new TempDBDelete();
			del.start();
		} catch (Exception E) {
			E.printStackTrace();
		}
	}

	public void run() {

		try {
			while (true) {
				long now = System.currentTimeMillis();
				if (lastRun == -1 || now - lastRun >= 86400000) {
					GregorianCalendar cal = new GregorianCalendar();
					cal.setTimeInMillis(now);
					cal.set(Calendar.HOUR_OF_DAY, 0);
					cal.set(Calendar.MINUTE, 0);
					cal.set(Calendar.SECOND, 0);
					cal.set(Calendar.MILLISECOND, 0);
					lastRun = cal.getTime().getTime();

					// System.out.println(new Timestamp(lastRun));

					int seconds = NetFSE.TEMP_DB_DELETE_HOURS * 3600;
					Class.forName("org.postgresql.Driver");
					int[] types = NetFSE.getTypes();
					String url = "jdbc:postgresql://localhost/"
							+ NetFSE.RESULT_DB_DATABASE;
					Properties props = new Properties();
					props.setProperty("user", NetFSE.RESULT_DB_USER);
					props.setProperty("password", NetFSE.RESULT_DB_PASSWORD);
					props.setProperty("client_encoding", "UTF8");

					Connection resultConnection = DriverManager.getConnection(
							url, props);
					Statement s = resultConnection.createStatement();
					Statement s2 = resultConnection.createStatement();
					// String str = NetFSEUtil.convertToHex("Traffic");
					String sql = "select Query_ID from Queries where TS is not null and trunc(EXTRACT(EPOCH FROM NOW())) - trunc(EXTRACT(EPOCH FROM TS)) > "
							+ seconds + " limit 100000 offset 5";
					// System.out.println(sql);
					ResultSet rs = s.executeQuery(sql);
					while (rs.next()) {
						String queryID = rs.getString("Query_ID");
						for (int i = 0; i < types.length; i++) {
							try {
								// s2.execute("drop table " + queryID + "_" +
								// types[i]);
							} catch (Exception E) {
								// no op
							}
						}
						s2.execute("drop table " + queryID);
						s2.execute("delete from Queries where Query_ID='"
								+ queryID + "'");
						s2.execute("delete from Query_Types where Query_ID='"
								+ queryID + "'");
					}
					rs.close();
					s.close();
					s2.close();
					resultConnection.close();
				} else {
					// System.out.println("TempDBDelete is sleeping");
					sleep(600000); // sleep for 10 minutes
				}
			}
		} catch (Exception E) {
			E.printStackTrace();
		}
		System.out.println("TempDBDelete thread exited on an error");
	}
}